<template>
    <div>
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload"
            :http-request="uploadImg" >
            <img v-if="img" :src="img" class="avatar" fit="contain">
            <span v-else class="text">上传图片</span>
            <i class="el-icon-circle-close"></i>
        </el-upload>
    </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'questionsAvatar',
  props: {
    img: {
      type: String,
      default: ''
    }
  },
  methods: {
    // 检查函数 判断文件的类型还有大小 return  true(继续上传)/false(停止上传)
    beforeAvatarUpload (file) {
      // jpeg png gif bmp
      this.$emit('update:img', URL.createObjectURL(file))
      //   this.img = URL.createObjectURL(file)
      const isJPG = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/bmp'
      ].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5 // 5M
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    uploadImg ({ file }) {
    //   console.log(file)
      var cos = new COS({
        SecretId: 'AKIDDOjv6GUebaeia2qQp342wvAZnIpF9rS2',
        SecretKey: 'V2VuMjyGUbadbaP2b2MeoCaksz494lKj'
      })
      cos.uploadFile({
        Bucket: 'byt-1319625772', /* 填写自己的 bucket，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: file.name, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: function (progressData) {
          //   console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        if (err) {
          this.$message.error('上传失败！')
        } else {
          this.$message.success('上传成功！')
          this.$emit('input', 'https://' + data.Location)
        }
      })
    }

  }

}
</script>

<style lang="scss" >
.avatar-uploader {
    display: inline-block;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    // overflow: hidden;
    width: 100px;
    height: 60px;
    line-height: 60px;
    font-size: 12px;
    color: #333;
    text-align: center;
    margin-left: 310px;
    margin-top: -200px;
    .avatar {
        width: 100px;
        height: 60px;
        object-fit: contain;

    }
}
.el-icon-plus::before{
          content:none
         }
.avatar-uploader:hover {
    border-color: #409eff;
}

.el-icon-circle-close {
    position: absolute;
    right: -5px;
    top: -5px;
    font-size: 18px;
    color: #999;
    background: #fff;
}</style>
